#include "mygraphicsview.h"
#include <QMouseEvent>
#include <QGraphicsItem>
#include <QtMath>

MyGraphicsView::MyGraphicsView(QWidget *parent) : QGraphicsView(parent)
{

}

void MyGraphicsView::keyPressEvent(QKeyEvent *event)
{
    emit keyPress(event);
    QGraphicsView::keyPressEvent(event);
}

void MyGraphicsView::mouseDoubleClickEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        QPoint point = event->pos();
        emit mouseDoubleClick(point);
    }
    QGraphicsView::mouseDoubleClickEvent(event);
}

void MyGraphicsView::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        QPoint point = event->pos();
        emit mousePress(point);
    }
    QGraphicsView::mousePressEvent(event);
}

void MyGraphicsView::mouseMoveEvent(QMouseEvent *event)
{
    QPoint point = event->pos();
    emit mouseMove(point);

    if (scene()->mouseGrabberItem())
    {
        QGraphicsItem *item = scene()->mouseGrabberItem();
        QPointF pos = item->pos();

        // 网格间距
        const int gridSize = 20;
        qreal x = round(pos.x() / gridSize) * gridSize;
        qreal y = round(pos.y() / gridSize) * gridSize;

        item->setPos(x, y);
    }

    QGraphicsView::mouseMoveEvent(event);
}

void MyGraphicsView::mouseReleaseEvent(QMouseEvent *event)
{
    QGraphicsView::mouseReleaseEvent(event);

    if(event->button() == Qt::LeftButton)
    {
        const int gridSize = 20;

        QList<QGraphicsItem*> selectedItems = scene()->selectedItems();

        // 对齐选中的每个图元
        for (QGraphicsItem *item : selectedItems)
        {
            // 获取图形项的当前坐标和边界矩形
            QPointF currentPos = item->pos();
            QRectF boundingRect = item->boundingRect();

            // 计算左上角相对于当前坐标的位置
            QPointF topLeftOffset = boundingRect.topLeft();

            // 计算左上角对齐的目标位置
            qreal alignedX = round((currentPos.x() + topLeftOffset.x()) / gridSize) * gridSize;
            qreal alignedY = round((currentPos.y() + topLeftOffset.y()) / gridSize) * gridSize;

            // 调整图形项的位置，使左上角对齐到网格
            item->setPos(alignedX - topLeftOffset.x(), alignedY - topLeftOffset.y());
        }
    }
}
